package c2.cross.business.ladder.record;

import c2.cross.business.base.CrossSubModule;
import c2.cross.business.ladder.LadderModule;
import c2.cross.business.ladder.common.LadderOppoDetail;
import c2.cross.business.ladder.common.LadderPVPRecord;
import cate.common.rpc.path.RpcLadderPath;
import cate.common.table.d.GDLadder;
import cate.game.pvp.ladder.common.*;
import cp.solution.rpc.RpcMsgHead;
import cp.solution.util.collection.ListKit;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
public class LadderRecordModule extends CrossSubModule<LadderModule> {
    @Getter
    private List<LadderPVPRecord> records;

    @Override
    public void initDependent() throws Exception {
        super.initDependent();
        this.records = useDb().ladder.getRecordsList();
        if(ListKit.isEmpty(this.records)) {
            log.info("天梯赛大神榜 从Mongo没有读取到数据");
            this.records = new ArrayList<>();
        } else {
            log.info("天梯赛排行榜 从Mongo读取到{}条数据", this.records.size());
        }
        // 监听RPC事件
        useRpcRecv().onFireAndForgetTemplate(RpcLadderPath.ADD_RECORD_G2C, LadderReportQuery.class, this::addRecords);
        useRpcRecv().onRequestResponseTemplate(RpcLadderPath.GET_MASTER_REPORTS, Integer.class, this::reportshHandler);

    }

    private LadderReportResult reportshHandler(RpcMsgHead rpcMsgHead, Integer limit) {
        log.info("收到天梯赛获取大神风采录像的请求，数量为 {}", limit);
        return new LadderRecordDo().getList(this,limit);
    }

    private void addRecords(RpcMsgHead rpcMsgHead, LadderReportQuery query) {
        log.info("收到天梯赛增加大神风采录像的请求 {}", query);
        new LadderRecordDo().exe(this,query);
    }

    public synchronized void addRecord(LadderPVPRecord pvpRecord){
        if (!records.isEmpty()) {
            if (records.size() >= GDLadder.REPLAY_SIZE_MAX_DSFC) {
                records.remove(0);
            }
        }
        this.records.add(pvpRecord);
    }

    public synchronized Collection<LadderPVPRecord> saveRecordsList() {
        return context.db.ladder.updateRecordsList(this.records);
    }

    @Override
    public void onShutdown() throws Exception {
        super.onShutdown();
        saveRecordsList();
    }

    public void clearRecords () {
        this.records.clear();
    }

    public synchronized void removeRecords() {
        context.db.ladder.removeRecords();
    }
}
